import React, { useState, useEffect } from 'react';
import { Upload, message, Modal } from 'antd';
import oss from '@/utils/oss/index';
import styles from './index.less';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import Api from '@/api'
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';

let OriginalData = {}
const Index = (props) => {
  const { IsHD } = JSON.parse(sessionStorage.getItem('USER')) || {};
  const { imgData, ImgVisible, setImgVisible, ThumbRatio } = props;

  const [uploadPicLoading, setUploadPicLoading] = useState(false);
  const [imgUrl, setImgUrl] = useState('');
  const [crop, setCrop] = useState({
    x: 0,
    y: 0,
    width: 200,
    height: 200,
    aspect: 16 / 9,
  });

  useEffect(() => {
    const w = ThumbRatio.Width
    const h = ThumbRatio.Height
    const aspect = w / h
    setCrop({
      ...crop,
      width: w*20,
      height: h*20,
      aspect 
    })
  },[ThumbRatio])

  // 封面上传部分
  const beforeUpload = (file) => {
    const mimeType = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/webp'];
    const isJPG = mimeType.includes(file.type);
    if (!isJPG) {
      message.error('您只能上传图片类型为jpg、png、bmp、webp、gif的图片');
    }
    const isLt2M = file.size / 1024 / 1024 < 4;
    if (!isLt2M) {
      message.error('图片大小必须小于4M！');
    }
    return isJPG && isLt2M;
  };

  // 自定义封面上传
  const handleCustomRequest = (options) => {
    setUploadPicLoading(true);
    const Name = options.file.name.slice(0, options.file.name.indexOf('.'));
    const ExtName = options.file.name.slice(options.file.name.lastIndexOf('.'));
    oss.ucuxin.uploader(
      {
        options,
        attachmentStr: `{"Path":"","AttachType":1,"Name":'${Name}',"ExtName":'${ExtName}',"ResizeMode":1,"SImgResizeMode":2,"CreateThumb":${IsHD},"autoResizeLargeImage":${!IsHD}}`,
        autoResizeLargeImage: !IsHD,
      },
      (res) => {
        if (res.Ret === 0) {
          OriginalData = {
            ...res.Data
          }
          setImgVisible(true);
          setImgUrl(res.Data.Url);
        } else {
          message.error('上传失败！');
        }
      },
    );
  };

  const onChange = newCrop => {
    setCrop({
      ...newCrop,
    })

  }

  const handleOk = () => {
    const { setImg } = props;

    Api.User.CropImage({
      url: imgUrl,
      x: crop.x,
      y: crop.y,
      width: crop.width,
      height: crop.height,
      displayWidth: OriginalData.Width > 760 ? 760 : OriginalData.Width,
      createThumb: IsHD,
      autoResizeLargeImage: !IsHD,
    }).then(res => {
      if(res.Ret === 0){
          setImg({
            Url: res.Data,
            OriginalUrl: imgUrl,
          });
          setImgVisible(false)
      }
    })
  }
  return (
    <div>
      <Upload
        className={styles.avatarUploader}
        name="avatar"
        showUploadList={false}
        beforeUpload={beforeUpload}
        customRequest={handleCustomRequest}
        accept="image/gif,image/png,image/jpeg,image/bmp,image/webp"
      >
        {imgData.Url ? (
          <img src={imgData.Url} alt="" className={styles.avatar} />
        ) : (
          <div className={styles.avatarUploaderTrigger}>
            {uploadPicLoading ? <LoadingOutlined /> : <PlusOutlined />}
            <br />
            {uploadPicLoading ? '正在上传...' : '上传图片'}
          </div>
        )}
      </Upload>
      <Modal
        title="图片裁剪"
        visible={ImgVisible}
        width={820}
        zIndex={9999}
        onOk={handleOk}
        maskClosable={false}
        onCancel={() => setImgVisible(false)}
      >
        <ReactCrop
          src={imgUrl}
          crop={crop}
          // style={{ height: '660px', width: '800px' }}
          onChange={(newCrop) => onChange(newCrop)}
        />
      </Modal>
    </div>
  );
};

export default Index;
